﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UserInterfaceLayer
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["logout"] == "1")
                Session["UserID"] = null;

            lblInvalidUsernameOrPassword.Visible = false;
            lblConnectionFailed.Visible = false;
            lblDisabledAccount.Visible = false;
            this.PreRender += Page_PreRender;
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Session["UserID"] != null)
                Response.Redirect("~/User/");
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                Session["UserID"] = null;
                DataAccessLayer.linqDatabaseDataContext db = new DataAccessLayer.linqDatabaseDataContext();
                DataAccessLayer.User User = DataAccessLayer.User.FindByUsername(db, txtUsername.Text);
                if (User == null || User.Password != txtPassword.Text)
                    lblInvalidUsernameOrPassword.Visible = true;
                else if (!User.Enable)
                    lblInvalidUsernameOrPassword.Visible = true;
                else
                    Session["UserID"] = User.UserID;
            }
            catch (Exception ex)
            {
                lblConnectionFailed.Visible = true;
                Response.Write(ex.Message);
            }
        }
    }
}